/*
 * Project: com.mmall.common.spring.interceptor
 *
 * File Created at 2019-10-20
 *
 * Copyright 2019 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.mmall.common.spring.interceptor;

import com.common.framework.context.UserSecurityContext;
import com.common.framework.dto.TokenDTO;
import com.common.framework.exception.AuthorizedException;
import com.common.framework.util.HttpUtil;
import com.mmall.common.spring.security.AuthHelper;
import com.mmall.common.spring.security.LoginRequired;
import com.mmall.common.spring.security.UserSecurityContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jianghucoding
 * @date 2019-10-20
 */
@Component
public class UserSecurityInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AuthHelper authHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 必须调用方法才做记录
        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }
        HandlerMethod method = (HandlerMethod) handler;
        boolean loginRequired = method.hasMethodAnnotation(LoginRequired.class);
        if (loginRequired) { // 如果需要进行权限访问
            String authorization = request.getHeader("Authorization");
            if(StringUtils.isEmpty(authorization)) {
                // 没有 token 没有访问权限，请登录后访问
                throw new AuthorizedException();
            }
            String token = HttpUtil.analysisAuthorization(authorization);
            TokenDTO tokenDTO = authHelper.analysisToken(token);
            // 设置当前用户在当前线程的上下文信息
            UserSecurityContextHolder.setContext(UserSecurityContext.builder().userId(tokenDTO.getUserId()).build());

        }
        // TODO - jianghu 字符串验证拦截过滤
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 处理完后 clear theadLocal 数据
        UserSecurityContextHolder.clear();
        super.afterCompletion(request, response, handler, ex);
    }
}
